
const path = require('path')
const fs = require('fs')

const MemoryFileSystem = require('memory-fs')

const pathMemoRoot = '/memfs/hap/demo/'

const rpkName = 'com.quickapp.demo.memfs.debug.rpk'

let entry = {
  'app': pathMemoRoot + '/src/app.ux?uxType=app',
}

function traverseDirSync (dir, files, arr) {
  const list = fs.readdirSync(dir)
  list.forEach(function (file) {
    const newArr = arr.slice()
    newArr.push(file)
    const filePath = path.join(dir, file)
    const stat = fs.statSync(filePath)
    if (stat && stat.isDirectory()) {
      traverseDirSync(filePath, files, newArr)
    }
    else {
      files.push(newArr.join('/'))
    }
  })
  return files
}

/**
 * 读取文件系统：对象形式，key为文件名或者目录名
 */
function readTestDataAsRoot(baseUrl) {

  const fileShortPathList = traverseDirSync(baseUrl, [], [])

  const fileNodeRoot = {}

  while (fileShortPathList.length > 0) {
    const fileShortPath = fileShortPathList.shift()
    const fileParseItem = path.parse(fileShortPath)
    const fileParseName = fileParseItem.base

    let curDir = fileNodeRoot

    // 目录作为对象
    if (fileParseItem.dir) {
      fileParseItem.dir.split('/').forEach(dirName => {
        curDir[dirName] = curDir[dirName] || {}
        curDir = curDir[dirName]
      })
    }
    // 读取文件
    curDir[fileParseName] = fs.readFileSync(path.join(baseUrl, fileShortPath))
  }

  // 目录
  fileNodeRoot['node_modules'] = {}
  fileNodeRoot['build'] = {}
  fileNodeRoot['dist'] = {}

  for (let page in fileNodeRoot.src) {
    if (fileNodeRoot.src[page] && fileNodeRoot.src[page]['index.ux']) {
      entry[page + '/index'] = pathMemoRoot + 'src/' + page + '/index.ux?uxType=page'
    }
  }

  return fileNodeRoot
}

/**
 * 初始化文件系统的数据
 */
function initProjectData (fileNode, parentDir = '', memFS) {
  if (!memFS) {
    memFS = new MemoryFileSystem()
  }

  memFS.mkdirpSync(pathMemoRoot + '/' + parentDir)

  for (const pathName in fileNode) {
    const pathItem = fileNode[pathName]

    if (Object.prototype.toString.call(pathItem) === '[object Object]') {
      // 目录
      initProjectData(pathItem, parentDir + '/' + pathName, memFS)
    }
    else {
      // 文件
      memFS.writeFileSync(pathMemoRoot + '/' + parentDir + '/' + pathName, pathItem)
    }
  }

  return memFS
}

/**
 * 生成webpack配置参数
 */
function packProjectOptions (memFS) {
  // FIX: 避免babel加载报错
  process.babelrc = false

  return {
    // 基本配置
    pathPjt: pathMemoRoot,
    pathSrc: pathMemoRoot + 'src',
    pathBuild: pathMemoRoot + 'build',
    pathDist: pathMemoRoot + 'dist',
    manifestPack: 'com.quickapp.demo.memfs',
    // webpack配置
    context: pathMemoRoot,
    entry: entry,
    output: {
      path: path.join(pathMemoRoot, 'build')
    }
  }
}

module.exports = {
  rpkName: rpkName,
  pathMemoRoot: pathMemoRoot,
  readTestDataAsRoot: readTestDataAsRoot,
  initProjectData: initProjectData,
  packProjectOptions: packProjectOptions
}